from django.shortcuts import render,HttpResponse
from django.views.decorators.csrf import csrf_exempt
import json
from app01 import models
from app01.utils.form import OrderModelForm
from app01.utils.pagination import Pagination
from django.http import JsonResponse
from app01.utils.datetime import rad_Datetime
from django.core import serializers
def order_list(request):
    if request.method == 'GET':
        # 传查询条件显示列表
        # 创建空字典
        data_dict = {}
        # 前端传过来的参数
        search_data = request.GET.get('q', '')
        if search_data:
            # 把前端传过来的参数放到字典里
            data_dict['title__contains'] = search_data
        queryset = models.Order.objects.filter(**data_dict).order_by("-status")
        #待支付

        No_pay=models.Order.objects.filter(status=1).values('price')
        No_payList=0

        for i in No_pay:
            No_payList+=i['price']

        #已付金额
        pay = models.Order.objects.filter(status=2).values('price')
        payList=0
        for i in pay:
           payList+=i['price']

        # 总金额
        sumpice = models.Order.objects.filter().values('price').all()
        sumpiceList=0
        for i in sumpice:
           sumpiceList+=i['price']

        page_object = Pagination(request, queryset)
        form = OrderModelForm()
        #修改oid为只读
        form.fields['oid'].widget.attrs = {'class': 'form-control', 'placeholder': '请输入订单号', 'readonly': 'readonly'}
        context = {'form': form,
                   'search_data': search_data,
                   'page_queryset': page_object.page_queryset,  # 分完页的数据
                   'page_string': page_object.html(), # 页码
                   'No_payList':No_payList,
                    'payList':payList,
                   'sumpiceList':sumpiceList,
                   }

        return render(request, 'order_list.html', context)
@csrf_exempt
def order_add(request):
        """新建订单 ajax请求"""
        if request.method == "GET":
            data_dict = {'status': True, 'data': None}
            orderNo = rad_Datetime()
            data_dict['data'] = orderNo
            return HttpResponse(json.dumps(data_dict))
        """接收用户提交的数据"""
        form = OrderModelForm(request.POST)
        if form.is_valid():
            #获取管理员ID
            form.instance.admin_id=request.session["info"]["id"]
            form.save()
            data_dict = {"status": True}
            return HttpResponse(json.dumps(data_dict))
        data_dict = {"status": False, "error": form.errors}
        return HttpResponse(json.dumps(data_dict))

def order_delete(request):
    """获取前端传过来的ID"""
    uid=request.GET.get("id")
    exists=models.Order.objects.filter(id=uid).exists()
    if not exists:
        return JsonResponse({"status":False,"error":"删除失败，不存在该数据"})
    models.Order.objects.filter(id=uid).delete()
    return JsonResponse({"status": True})

def order_edit(request):
    """获取前端传过来的ID"""
    uid = request.GET.get("id")
    # 获取对象字典
    row_object=models.Order.objects.filter(id=uid).values('oid','title','price','status').first()
    if not row_object:
        return JsonResponse({"status":False,"error":"不存在该数据"})
    result={'status':True,
            'data':row_object
            }
    return JsonResponse(result)
@csrf_exempt
def order_editDetailed(request):
    """提交编辑"""
    uid=request.GET.get("uid")
    row_object=models.Order.objects.filter(id=uid).first()
    if not row_object:
        return JsonResponse({"status": False, "tips": "数据不存在！"})
    form=OrderModelForm(request.POST,instance=row_object)
    if form.is_valid():
        form.save()
        return JsonResponse({"status": True})
    data_dict = {"status": False, "error": form.errors}
    return HttpResponse(json.dumps(data_dict))